package org.deyang.tools.amazon;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;

public class StartWeiboPostWorkServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6989949765145070908L;
	private static final Logger log = Logger.getLogger(StartWeiboPostWorkServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		String code = req.getParameter("code");
		URL tokenurl = new URL("https://api.weibo.com/oauth2/access_token");
		String tokenurlpara = "client_id=3201307572&client_secret=de5a3193866c9668efe79f5d5451d6e4&grant_type=authorization_code&redirect_uri=" + URLEncoder.encode("http://aaasearchengine.appspot.com/weibopostprocessor", "UTF-8") + "&code=" + code;
		HttpURLConnection tokenConn = (HttpURLConnection) tokenurl.openConnection();
		tokenConn.setDoOutput(true);
		tokenConn.setDoInput(true);
		tokenConn.setRequestProperty("Content-Length", "" + Integer.toString(tokenurlpara.getBytes().length));
		tokenConn.setRequestMethod("POST");
		//Send request
        DataOutputStream wr = new DataOutputStream(tokenConn.getOutputStream ());
        wr.writeBytes (tokenurlpara);
        wr.flush ();
        wr.close ();
        
        //Get Response	
        StringWriter writer = new StringWriter();
        IOUtils.copy(tokenConn.getInputStream(), writer);
        log.warning(writer.toString());
        JSONObject tokenResult = (JSONObject) JSONValue.parse(writer.toString());
        int i = 0;
        if (tokenResult.containsKey("access_token")){
        	Query weiboq = new Query("AmazonProduct");
			weiboq.addFilter("isPendingToWeibo", Query.FilterOperator.EQUAL, true);
			DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			PreparedQuery pq = datastore.prepare(weiboq);
			for (Entity result : pq.asIterable()){
				Queue queue = QueueFactory.getQueue("weibopostqueue");
			    queue.add(TaskOptions.Builder.withUrl("/weibopostworker")
			    		.param("token", (String) tokenResult.get("access_token"))
			    		.param("asin", (String)result.getProperty("asin")));
			    result.setProperty("isPendingToWeibo", false);
			    datastore.put(result);
			    i++;
			}
			resp.getWriter().println("Authoration successful, will post " + i + " entries!");
        	resp.setStatus(200);
        }else{
        	log.warning("get weibo access_token error");
        	resp.getWriter().println("Authoration failed");
        	resp.setStatus(400);
        }
		
	

	}
}
